﻿using System;
using System.ComponentModel;
using System.Web.UI;

namespace MyLib.Web.UI {
	/// <summary>
	/// 
	/// </summary>
	[ParseChildren(true)]
	[Obsolete("Use embeded script instead.", true)]
	public class MyIf : Control, INamingContainer {
		/// <summary>
		/// 
		/// </summary>
		[Browsable(false)]
		[DefaultValue("")]
		[TemplateContainer(typeof(ItemTemplateContent))]
		[TemplateInstance(TemplateInstance.Single)]
		[PersistenceMode(PersistenceMode.InnerProperty)]
		public ITemplate IsTrue { get; set; }

		/// <summary>
		/// 
		/// </summary>
		[Browsable(false)]
		[DefaultValue("")]
		[TemplateContainer(typeof(ItemTemplateContent))]
		[TemplateInstance(TemplateInstance.Single)]
		[PersistenceMode(PersistenceMode.InnerProperty)]
		public ITemplate IsFalse { get; set; }

		/// <summary>
		/// 
		/// </summary>
		[Bindable(BindableSupport.Yes, BindingDirection.OneWay)]
		[DefaultValue(false)]
		public object Test { get; set; }

		private object m_dataItem = null;

		private bool m_requiresDataBinding = false;

		/// <summary>
		/// 
		/// </summary>
		/// <param name="writer"></param>
		protected override void Render(HtmlTextWriter writer) {
			RenderChildren(writer);
		}

		/// <summary>
		/// 
		/// </summary>
		protected override void CreateChildControls() {
			Controls.Clear();

			var ct = Convert.ToString(Test);
			var bt = false;

			if (!string.IsNullOrWhiteSpace(ct)) {
				ct = ct.Trim().ToLower();

				bt = ct == "true" || ct == "yes" || ct == "1";
			}

			var itc = new ItemTemplateContent(m_dataItem, 0, 0);

			if (bt) {
				if (IsTrue != null)
					IsTrue.InstantiateIn(itc);
			} else {
				if (IsFalse != null)
					IsFalse.InstantiateIn(itc);
			}

			Controls.Add(itc);

			if (m_requiresDataBinding) {
				itc.DataBind();
			}

			ChildControlsCreated = true;
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="e"></param>
		protected override void OnDataBinding(EventArgs e) {
			m_dataItem = Page.GetDataItem();
			m_requiresDataBinding = true;

			base.OnDataBinding(e);
		}
	} // end of IIf.
}
